﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// 资源配置
/// </summary>
public class AssetsSetting
{
    public INIReader ini;
    string Name;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="name">资源名</param>
    /// <param name="path">文件路径</param>
    public AssetsSetting(string name, string path)
    {
        Name = name;
        ini = new INIReader();
        if (path != null & path != "")
            ini.LoadFromFile(path);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="name">资源名</param>
    /// <param name="data">资源数据</param>
    public AssetsSetting(string name, byte[] data)
    {
        Name = name;
        ini = new INIReader();
        ini.LoadData(data);
    }
    public void Clear()
    {
        ini = null;
    }

    bool Changed;
    public string GetString(string block, string name)
    {
        var sec = ini.FindSection(block);
        if (sec == null)
            return null;
        return sec.GetValue(name);
    }
    public int GetInt(string block, string name)
    {
        var sec = ini.FindSection(block);
        if (sec == null)
            return 0;
        string v = sec.GetValue(name);
        if (v == null)
            return 0;
        int a = 0;
        int.TryParse(v, out a);
        return a;
    }
    public void SetString(string block, string name, string value)
    {
        var sec = ini.FindSection(block);
        if (sec == null)
        {
            sec = new INISection();
            sec.Name = block;
            ini.AddSection(sec);
        }
        Changed = true;
        sec.Add(name, value);
    }
    public void SetInt(string block, string name, int value)
    {
        var sec = ini.FindSection(block);
        if (sec == null)
        {
            sec = new INISection();
            sec.Name = block;
            ini.AddSection(sec);
        }
        Changed = true;
        sec.Add(name, value.ToString());
    }
    public void Save()
    {
        if (Changed)
        {
            ini.WriteToFile(Environment.CurrentDirectory + "/" + Name);
            Changed = false;
        }
    }
    public void RemoveBlock(string block)
    {
        if (ini != null)
        {
            if (ini.RemoveSection(block))
                Changed = true;
        }
    }
}
